class Solution:
  def exist(self, board: list, word: str) -> bool:
    def dfs(i, j, k):
      # self.print_board(board)
      if not 0 <= i < len(board) or not 0 <= j < len(board[0]) or board[i][j] != word[k]:
        return False
      if k == len(word) - 1:
        return True
      tmp = board[i][j]
      board[i][j] = '/'
      res = dfs(i-1, j, k+1) or dfs(i+1, j, k+1) or dfs(i, j-1, k+1) or dfs(i, j+1, k+1)
      board[i][j] = tmp
      return res
    
    for i in range(len(board)):
      for j in range(len(board[0])):
        if dfs(i, j, 0):
          return True
    return False
  
  def print_board(self, board):
    for i in range(len(board)):
      for j in range(len(board[0])):
        print(board[i][j], end=' ')
      print('')
    print('----------')


'''
STATUS: LEARNT
TRIES:  N/A
TIME:   248 MS
MEMORY: 14.9 MB
'''
if __name__ == "__main__":
  solution = Solution()
  # board = [
  #   ['A', 'B', 'C', 'E'],
  #   ['S', 'F', 'C', 'S'],
  #   ['A', 'D', 'E', 'E']
  # ]
  # word = 'ABCCED'
  board = [
    ['a', 'b'],
    ['c', 'd']
  ]
  word = 'abcd'
  print(solution.exist(board, word))